package com.zt.bus.order.service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.zt.bus.sms.service.SendCodeService;
import com.zt.util.PropertiesUtil;
import net.sf.json.groovy.GJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zt.bus.constant.BusConstant;
import com.zt.bus.line.model.Line;
import com.zt.bus.line.model.LinePlan;
import com.zt.bus.line.model.Refund;
import com.zt.bus.line.service.LinePlanService;
import com.zt.bus.line.service.LineService;
import com.zt.bus.line.service.RefundService;
import com.zt.bus.order.inter.OrderBackDetailMapper;
import com.zt.bus.order.inter.OrderBackMapper;
import com.zt.bus.order.inter.OrderDetailMapper;
import com.zt.bus.order.model.Order;
import com.zt.bus.order.model.OrderBack;
import com.zt.bus.order.model.OrderBackDetail;
import com.zt.bus.order.model.OrderBackInfo;
import com.zt.bus.order.model.OrderBackRefund;
import com.zt.bus.order.model.OrderDetail;
import com.zt.bus.order.model.OrderDetailPassenger;
import com.zt.bus.order.model.OrderPayment;
import com.zt.bus.order.model.OrderDetailPassenger.OrderDate;
import com.zt.servlet.FieldAlias;
import com.zt.servlet.ReqBean;
import com.zt.shiro.GlobalInput;
import com.zt.system.model.BusinessException;
import com.zt.system.model.SqlBuilder;
import com.zt.system.service.BaseService;
import com.zt.util.DateUtil;
import com.zt.util.StringUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 订单退订
 * 
 * @author zwm
 * @date 2017-06-16
 */
@Service
public class OrderBackService extends BaseService {
    @Autowired
    private OrderBackMapper orderBackMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private OrderBackDetailMapper orderBackDetailMapper;
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderAmountService orderAmountService;
    @Autowired
    private RefundService refundService;
    @Autowired
    private LineService lineService;
    @Autowired
    private LinePlanService linePlanService;
    @Autowired
    private OrderPaymentService orderPaymentService;

    @Autowired
    private SendCodeService sendCodeService;

    // 申请退款短信模版id
    public static final String APPLY_REFUND_ID = PropertiesUtil.getProperty("apply_refund_id");

    // 新线招募取消模版id
    public static final String LINE_CANCEL = PropertiesUtil.getProperty("line_cancel");

    /**
     * 查询
     * 
     * @param reqBean
     * @return
     */
    public JSONObject getTable(ReqBean reqBean) {
        SqlBuilder sqlBuilder = new SqlBuilder(
                "SELECT o.LINE_NAME,o.BOOK_USER_PHONE,ob.*,ob.REFUND_AMOUNT-ob.REFUND_FEE as 'refundMoney' FROM DZ_ORDER_BACK ob");
        sqlBuilder.appendSql(" LEFT JOIN DZ_ORDER o on ob.ORDER_ID=o.ORDER_ID  WHERE 1 = 1");
        sqlBuilder.addWhereLike2("ob.ORDER_ID", reqBean.getInfo("orderId"));
        sqlBuilder.addWhere("ob.C_ORDER_BACK_TYPE", reqBean.getInfo("orderBackType"));
        sqlBuilder.addWhere("o.BOOK_USER_PHONE", reqBean.getInfo("bookUserPhone"));
        sqlBuilder.addWhere("ob.C_ORDER_BACK_STATUS", reqBean.getInfo("orderBackStatus"));
        sqlBuilder.appendSql(" order by ob.MAKE_TIME desc");
        JSONObject result = this.queryTable(sqlBuilder, reqBean.getPageSize(), reqBean.getPageIndex());
        JSONArray rows = result.getJSONArray("rows");
        // 金额格式化
        for (int i = 0; i < rows.size(); i++) {
            JSONObject json = rows.getJSONObject(i);
            double refundMoney = json.getDouble("refundMoney");
            json.put("refundMoney", String.valueOf(refundMoney));
        }
        return result;
    }
    
    /**
     * 退订订单列表
     * 
     * @param bookUserPhone
     * @return
     */
    @FieldAlias(service = "codeService", field = "orderBackStatus", alias = "orderBackStatusName", param = "orderbackstatus")
    public JSONArray getOrderBackByPhone(String bookUserPhone) {
        if (StringUtil.isEmpty(bookUserPhone)) {
            throw new BusinessException("获取用户信息失败!");
        }
        ReqBean reqBean = new ReqBean();
        reqBean.addInfo("bookUserPhone", bookUserPhone);

        SqlBuilder sqlBuilder = new SqlBuilder(
                "SELECT o.DEPART_TIME,o.CASH_AMOUNT,o.LINE_NAME,o.BOOK_USER_PHONE,ob.C_ORDER_BACK_STATUS,ob.ORDER_ID,ob.DAYS,ob.MAKE_TIME,"
                        + "ob.ORDER_BACK_ID,ob.REFUND_AMOUNT,ob.REFUND_FEE,ob.REFUND_AMOUNT-ob.REFUND_FEE as 'refundMoney' FROM DZ_ORDER_BACK ob");
        sqlBuilder.appendSql(" LEFT JOIN DZ_ORDER o on ob.ORDER_ID=o.ORDER_ID  WHERE 1 = 1");
        sqlBuilder.addWhere("o.BOOK_USER_PHONE", reqBean.getInfo("bookUserPhone"));
        sqlBuilder.appendSql(" order by ob.MAKE_TIME desc");
        return query(sqlBuilder);
    }

    /**
     * 通过orderBackId查询退订明细
     * 
     * @param orderBackId
     * @return
     */
    @FieldAlias(service = "codeService", field = "orderBackStatus", alias = "orderBackStatusName", param = "orderbackstatus")
    public JSONObject getOrderBackDetailById(String orderBackId) {
        SqlBuilder sqlBuilder = new SqlBuilder(
                "SELECT ob.C_ORDER_BACK_STATUS,o.LINE_ID,o.PRICE,o.DEPART_TIME,o.CASH_AMOUNT,o.LINE_NAME,o.BOOK_USER_PHONE,ob.ORDER_BACK_ID,ob.DAYS,ob.REFUND_AMOUNT,ob.REFUND_FEE,ob.REFUND_AMOUNT-ob.REFUND_FEE as 'refundMoney',ob.REASON FROM DZ_ORDER_BACK ob");
        sqlBuilder.appendSql(" LEFT JOIN DZ_ORDER o on ob.ORDER_ID=o.ORDER_ID  WHERE 1 = 1");
        sqlBuilder.addWhere(" ob.ORDER_BACK_ID", orderBackId);
        sqlBuilder.appendSql(" order by ob.MAKE_TIME desc");

        JSONObject json = new JSONObject();
        JSONArray oederBackArray = query(sqlBuilder);
        if (oederBackArray != null && oederBackArray.size() > 0) {
            json = oederBackArray.getJSONObject(0);
        }

        List<OrderDetail> list = orderDetailMapper.selectByOrderBackId(orderBackId);
        JSONArray array = new JSONArray();
        JSONObject jsonObject = null;
        // 查询出对应的订单详情明细
        for (OrderDetail orderDetail : list) {
            if (jsonObject == null || !orderDetail.getPassengerPhone().equals(jsonObject.getString("passengerPhone"))) {
                array.add(new JSONObject());
                jsonObject = array.getJSONObject(array.size() - 1);
                jsonObject.put("passengerPhone", orderDetail.getPassengerPhone());
                jsonObject.put("passengerName", orderDetail.getPassengerName());
                jsonObject.put("onStop", lineService.getStop(orderDetail.getOnStopId()).getStopName());
                jsonObject.put("dates", new JSONArray());
            }
            JSONObject date = new JSONObject();
            date.put("date", DateUtil.formatDate(orderDetail.getRideDate()));
            jsonObject.getJSONArray("dates").add(date);
        }
        json.put("passengers", array);

        String lineId = json.optString("lineId");
        if (StringUtil.isNotEmpty(lineId)) {
            Line line = lineService.getById(lineId);
            json.put("lineType", line == null ? "" : line.getLineType());
        }
        return json;
    }

    /**
     * 用户申请退款
     * 
     * @param orderId
     * @param reason
     * @param orderBackInfos
     */
    public void apply(String orderId, String reason, String orderBackType, List<OrderBackInfo> orderBackInfos) {
        if (StringUtil.isEmpty(orderId)) {
            throw new BusinessException("缺少参数！");
        }
        if (orderBackInfos == null || orderBackInfos.size() == 0) {
            throw new BusinessException("申请退订数据为空");
        }

        // 如果该订单有未处理的订单(退款申请、退款处理中)，不允许再次申请退款
        List<OrderBack> orderBackList_apply = orderBackMapper.selectByOrderIdAndStatus(orderId,
                BusConstant.OrderBackStatus.REFUND_APPLY);
        if (orderBackList_apply != null && orderBackList_apply.size() > 0) {
            throw new BusinessException("该订单目前还有申请退款的退订任务，不能继续申请退款");
        }
        List<OrderBack> orderBackList_refunding = orderBackMapper.selectByOrderIdAndStatus(orderId,
                BusConstant.OrderBackStatus.REFUNDING);
        if (orderBackList_refunding != null && orderBackList_refunding.size() > 0) {
            throw new BusinessException("该订单目前还有处理中的退订任务，不能继续申请退款");
        }

        Order order = orderService.getById(orderId);

        // 每个乘客的退款方案
        List<OrderBackRefund> orderBackRefunds = orderAmountService.getOrderBackRefunds(orderId, orderBackInfos);
        // 请求退款的订单明细
        List<OrderDetail> orderDetails = getOrderBackDetails(order, orderBackInfos);

        OrderBack orderBack = new OrderBack();
        orderBack.setOrderBackId(stringId());
        orderBack.setOrderId(order.getId());
        orderBack.setOrderBackType(orderBackType);// 订单退订类型 1、乘客退订 2、管理员退订
        orderBack.setDays(orderDetails.size());// 退订天数

        orderBack.setCashValue(0.0);// 退订订单现金价
        double backTotalAmount = 0, backTotalFee = 0;
        for (OrderBackRefund backRefund : orderBackRefunds) {
            backTotalFee += backRefund.getBackFee();// 整个订单总的手续费
        }
        if (orderDetails.size() == 0) {
            throw new BusinessException("请选择退款日期!");
        }

        LinePlan linePlan = linePlanService.getById(order.getPlanId());
        if (linePlan == null) {
            throw new BusinessException("线路方案不存在!");
        }
        // 待开方案处理（订单全退）
        if (BusConstant.LinePlanStatus.TO_BE_OPEN.equals(linePlan.getPlanStatus())) {
            // 获取订单全部明细
            List<OrderDetail> list = orderDetailMapper.selectByOrderId(orderId);
            if (list.size() > orderDetails.size()) {
                throw new BusinessException("该订单属于待开方案，订单必须全部退款!");
            }
        }

        backTotalAmount = orderAmountService.getRefundAmount(orderBack.getDays(), order, orderBack.getOrderBackType());
        if (backTotalAmount > 0) {
            Refund refund = refundService.getRefundByPlanId(order.getPlanId());// 退款方案
            backTotalFee = backTotalFee >= refund.getMinimumFee() ? backTotalFee : refund.getMinimumFee(); // 最低手续费
        } else {// 没钱可退
            backTotalFee = 0;
            backTotalAmount = 0;
        }
        if (BusConstant.OrderBackType.BACK_ADMIN.equals(orderBack.getOrderBackType())) {// 管理员后台手动退订，不扣除手续费
            backTotalFee = 0;
        }

        BigDecimal b1 = new BigDecimal(Double.toString(backTotalAmount));
        BigDecimal b2 = new BigDecimal(Double.toString(backTotalFee));
        DecimalFormat df = new DecimalFormat("######0.00");

        orderBack.setRefundAmount(Double.valueOf(df.format(b1)));// 订单退款金额
        orderBack.setRefundFee(Double.valueOf(df.format(b2)));// 退款总手续费
        orderBack.setReason(reason);// 退款原因
        orderBack.setOrderBackStatus(BusConstant.OrderBackStatus.REFUND_APPLY);// 订单退订状态(申请退款)
        orderBack.setMakeTime(new Date());
        orderBack.setModifyTime(orderBack.getMakeTime());
        orderBackMapper.insert(orderBack);

        // 记录每条明细的手续费折扣
        Map<String, OrderBackRefund.OrderBackRefundDetail> map = new HashMap<>();
        for (OrderBackRefund backRefund : orderBackRefunds) {
            for (OrderBackRefund.OrderBackRefundDetail orderBackRefundDetail : backRefund.getDetails()) {
                map.put(backRefund.getPhone() + orderBackRefundDetail.getDate(), orderBackRefundDetail);
            }
        }
        // 保存退订订单明细
        for (OrderDetail orderDetail : orderDetails) {
            OrderBackDetail orderBackDetail = new OrderBackDetail();
            orderBackDetail.setId(stringId());// 订单退订明细ID
            orderBackDetail.setOrderBackId(orderBack.getOrderBackId());// 订单退订ID
            orderBackDetail.setOrderDetailId(orderDetail.getId());// 订单明细ID
            orderBackDetail.setRefundDetailId(map.get(
                    orderDetail.getPassengerPhone() + DateUtil.formatDate(orderDetail.getRideDate()))
                    .getRefundDetailId());
            orderBackDetailMapper.insert(orderBackDetail);

            // 修改订单明细状态
            orderDetail.setStatus(BusConstant.OrderBackStatus.REFUND_APPLY);
            orderDetailMapper.updateByPrimaryKey(orderDetail);
        }
        if (BusConstant.OrderBackType.BACK_ADMIN.equals(orderBack.getOrderBackType())) {// 管理员后台手动退订，不需要再审核
            agree(orderBack.getOrderBackId());// 退款
        }

        // 发送退款申请短信
        boolean result = sendCodeService.sendSms(orderBack.getOrderBackId(),order.getBookUserPhone(), null, "退款受理短信", APPLY_REFUND_ID);
        if(!result) {
            throw new BusinessException("退款受理短信发送失败!");
        }

    }

    /**
     * 退款申请通过
     * 
     * @param orderBackId
     */
    public JSONObject agree(String orderBackId) {
        Date date = new Date();
        if (StringUtil.isEmpty(orderBackId)) {
            throw new BusinessException("缺少参数");
        }
        OrderBack orderBack = orderBackMapper.selectByPrimaryKey(orderBackId);
        if (orderBack == null) {
            throw new BusinessException("退订订单不存在");
        }

        JSONObject returnJson = new JSONObject();
        double refundFee = orderBack.getRefundFee();// 手续费
        double refundAmount = orderBack.getRefundAmount();// 订单退款金额
        double refundMoney = refundAmount - refundFee;// 实际应退金额
        if (refundMoney > 0) {
            // 退款
            returnJson.put("payStatus", orderPaymentService.createOrderBackPayment(orderBack).getPayStatus());
        } else {// 没钱可退,直接将退订订单状态改为退款成功
            String orderBackStatus = BusConstant.OrderBackStatus.REFUND_SUCCESS;
            // 修改退款订单状态
            orderBack.setOrderBackStatus(orderBackStatus);// 退款中
            orderBack.setAuditTime(date);
            orderBack.setAuditUserId(GlobalInput.getCurrentUserId());
            orderBack.setModifyTime(orderBack.getAuditTime());
            orderBackMapper.updateByPrimaryKey(orderBack);

            // 修改订单明细状态
            List<OrderDetail> details = orderDetailMapper.selectByOrderBackId(orderBackId);
            for (OrderDetail detail : details) {
                detail.setStatus(orderBackStatus);
                orderDetailMapper.updateByPrimaryKey(detail);
            }
        }
        return returnJson;
    }

    /**
     * 退款申请驳回
     * 
     * @param orderBackId
     */
    public void reject(String orderBackId) {
        if (StringUtil.isEmpty(orderBackId)) {
            throw new BusinessException("缺少参数");
        }
        OrderBack orderBack = orderBackMapper.selectByPrimaryKey(orderBackId);
        if (orderBack == null) {
            throw new BusinessException("退订订单不存在");
        }

        // 修改退款订单状态
        orderBack.setOrderBackStatus(BusConstant.OrderBackStatus.REFUND_REJECT);// 退款驳回
        orderBack.setAuditTime(new Date());
        orderBack.setAuditUserId(GlobalInput.getCurrentUserId());
        orderBack.setModifyTime(orderBack.getAuditTime());
        orderBackMapper.updateByPrimaryKey(orderBack);

        // 修改订单明细状态
        List<OrderDetail> details = orderDetailMapper.selectByOrderBackId(orderBackId);
        for (OrderDetail detail : details) {
            detail.setStatus(BusConstant.OrderDetailStatus.PAYMENT_SUCCESSFUL);// 驳回改回支付成功状态
            orderDetailMapper.updateByPrimaryKey(detail);
        }
    }

    private List<OrderBackInfo> getOrderBackInfoList(List<OrderDetailPassenger> passengers) {
        List<OrderBackInfo> list = new ArrayList<>();
        for (int i = 0; i < passengers.size(); i++) {
            OrderBackInfo orderBackInfo = new OrderBackInfo();
            OrderDetailPassenger passenger = passengers.get(i);
            orderBackInfo.setPassengerName(passenger.getPassengerName());
            orderBackInfo.setPassengerPhone(passenger.getPassengerPhone());

            List<String> dates = new ArrayList<>();
            List<OrderDate> dateList = passenger.getDates();

            for (int j = 0; j < dateList.size(); j++) {
                OrderDate orderDate = dateList.get(j);
                dates.add(DateUtil.formatDate(orderDate.getDate()));
            }
            orderBackInfo.setDates(dates);
            list.add(orderBackInfo);
        }
        return list;
    }

    /**
     * 处理未发车的乘客已经订单信息
     * 
     * @param passengers
     * @return
     */
    private Map<String, List<OrderDetailPassenger>> getPassengerMap(List<OrderDetailPassenger> passengers) {
        Map<String, List<OrderDetailPassenger>> maps = new HashMap<String, List<OrderDetailPassenger>>();
        for (OrderDetailPassenger orderDetailPassenger : passengers) {
            String orderId = orderDetailPassenger.getOrderId();
            if (maps.containsKey(orderId)) {
                maps.get(orderId).add(orderDetailPassenger);
            } else {
                List<OrderDetailPassenger> new_list = new ArrayList<OrderDetailPassenger>();
                new_list.add(orderDetailPassenger);
                maps.put(orderId, new_list);
            }
        }
        return maps;
    }

    /**
     * 线路停运，直接退款，不收手续费
     * 
     * @param planId
     */
    public void closePlan(String planId) {
        List<OrderDetailPassenger> passengers = orderService.getNotDepartOrders(planId);
        // 处理未发车的乘客已经订单信息
        Map<String, List<OrderDetailPassenger>> passengerMaps = getPassengerMap(passengers);

        for (Map.Entry<String, List<OrderDetailPassenger>> entry : passengerMaps.entrySet()) {
            String orderId = entry.getKey();

            Order order = orderService.getById(orderId);
            // 未支付(待支付、支付失败)的订单直接关闭
            if (BusConstant.OrderStatus.TO_BE_PAID.equals(order.getStatus())
                    || BusConstant.OrderStatus.PAYMENT_FAILED.equals(order.getStatus())) {
                orderService.cancel(order.getId());// 取消订单
            } else {
                // 退订明细
                List<OrderBackInfo> orderBackInfos = getOrderBackInfoList(entry.getValue());
                // 每个乘客的退款方案
                List<OrderBackRefund> orderBackRefunds = orderAmountService
                        .getOrderBackRefunds(orderId, orderBackInfos);
                // 请求退款的订单明细
                List<OrderDetail> orderDetails = getOrderBackDetails(order, orderBackInfos);

                OrderBack orderBack = new OrderBack();
                orderBack.setOrderBackId(stringId());
                orderBack.setOrderId(order.getId());
                orderBack.setOrderBackType(BusConstant.OrderBackType.BACK_ADMIN);// 订单退订类型
                                                                                 // 1、乘客退订
                                                                                 // 2、管理员退订
                orderBack.setDays(orderDetails.size());// 退订天数

                orderBack.setCashValue(0.0);// 退订订单现金价
                double backTotalAmount = 0;

                // 获得整个退订订单的退款金额
                backTotalAmount = orderAmountService.getRefundAmount(orderBack.getDays(), order,
                        BusConstant.OrderBackType.BACK_ADMIN);

                if (backTotalAmount <= 0) {
                    backTotalAmount = 0;
                }

                BigDecimal b1 = new BigDecimal(Double.toString(backTotalAmount));
                DecimalFormat df = new DecimalFormat("######0.00");

                orderBack.setRefundAmount(Double.valueOf(df.format(b1)));// 订单退款金额
                orderBack.setRefundFee(0);// 退款总手续费(管理员退订没有手续费)
                orderBack.setReason("方案取消");// 退款原因
                orderBack.setOrderBackStatus(BusConstant.OrderBackStatus.REFUND_SUCCESS);// 订单退订状态(申请退款)
                orderBack.setMakeTime(new Date());
                orderBack.setModifyTime(orderBack.getMakeTime());
                orderBackMapper.insert(orderBack);

                // 记录每条明细的手续费折扣
                Map<String, OrderBackRefund.OrderBackRefundDetail> map = new HashMap<>();
                for (OrderBackRefund backRefund : orderBackRefunds) {
                    for (OrderBackRefund.OrderBackRefundDetail orderBackRefundDetail : backRefund.getDetails()) {
                        map.put(backRefund.getPhone() + orderBackRefundDetail.getDate(), orderBackRefundDetail);
                    }
                }
                // 保存退订订单明细
                for (OrderDetail orderDetail : orderDetails) {
                    OrderBackDetail orderBackDetail = new OrderBackDetail();
                    orderBackDetail.setId(stringId());// 订单退订明细ID
                    orderBackDetail.setOrderBackId(orderBack.getOrderBackId());// 订单退订ID
                    orderBackDetail.setOrderDetailId(orderDetail.getId());// 订单明细ID
                    orderBackDetail.setRefundDetailId(map.get(
                            orderDetail.getPassengerPhone() + DateUtil.formatDate(orderDetail.getRideDate()))
                            .getRefundDetailId());
                    orderBackDetailMapper.insert(orderBackDetail);

                    // 修改订单明细状态
                    orderDetail.setStatus(BusConstant.OrderBackStatus.REFUND_SUCCESS);
                    orderDetailMapper.updateByPrimaryKey(orderDetail);
                }

                // 退款
                if (orderBack.getRefundAmount() > 0) {
                    orderPaymentService.createOrderBackPayment(orderBack);
                    // 发送退款申请短信
                    JSONObject json = new JSONObject();
                    json.put("line",order.getLineName());
                    json.put("date",DateUtil.formatDateTime(new Date()));
                    boolean result = sendCodeService.sendSms(orderBack.getOrderBackId(), order.getBookUserPhone(), json.toString(), "新线招募取消短信", LINE_CANCEL);
                    if(!result) {
                        throw new BusinessException("新线招募取消短信发送失败!");
                    }
                }
            }
        }
    }

    /**
     * 获取退订明细
     * 
     * @param order
     * @param orderBackInfos
     * @return
     */
    public List<OrderDetail> getOrderBackDetails(Order order, List<OrderBackInfo> orderBackInfos) {
        List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(order.getId()), list = new ArrayList<>();
        Map<String, OrderDetail> map = new HashMap<>();
        for (OrderDetail detail : orderDetails) {
            map.put(detail.getPassengerPhone() + DateUtil.formatDate(detail.getRideDate()), detail);
        }

        for (OrderBackInfo orderBackInfo : orderBackInfos) {
            String passengerPhone = orderBackInfo.getPassengerPhone();
            List<String> dates = orderBackInfo.getDates();// 乘客退订的日期
            for (String date : dates) {
                OrderDetail orderDetail = map.get(passengerPhone + date);
                if (orderDetail == null) {
                    // throw new BusinessException("订单明细不存在！");
                    System.out.println("订单明细不存在！");
                    continue;
                }
                if (BusConstant.OrderDetailStatus.REFUND_SUCCESS.equals(orderDetail.getStatus())) {
                    // throw new BusinessException("订单明细状态不存在！");
                    System.out.println("订单明细状态不存在！");
                    continue;
                }
                if (OrderService.isDepart(new Date(), DateUtil.parse(date), order.getDepartTime())) {
                    System.out.println(date + "日订单已发车！");
                    continue;
                    // throw new BusinessException(date + "日订单已发车！");
                }
                list.add(orderDetail);
            }
        }
        return list;
    }

    /**
     * 查询该订单已退订单
     * 
     * @param orderId
     * @return
     */
    public List<OrderBack> getRefundedOrder(String orderId) {
        return orderBackMapper.selectByOrderIdAndStatus(orderId, BusConstant.OrderBackStatus.REFUND_SUCCESS);
    }

    /**
     * 获得本订单用户主动退款订单
     * 
     * @param orderId
     * @return
     */
    public List<OrderBack> getOrderBackListByUser(String orderId) {
        return orderBackMapper.selectByOrderIdAndOrderBackType(orderId, BusConstant.OrderBackType.BACK_USER);
    }

    /**
     * 通过id查询
     * 
     * @param orderBackId
     * @return
     */
    public OrderBack getById(String orderBackId) {
        return orderBackMapper.selectByPrimaryKey(orderBackId);
    }

    /**
     * 修改退订订单、订单明细状态 用于支付完成后回调
     * 
     * @param orderBackId
     * @param status
     */
    public void updateOrderBackStatus(String orderBackId, String status) {
        OrderBack orderBack = orderBackMapper.selectByPrimaryKey(orderBackId);
        if (orderBack == null) {
            throw new BusinessException("退订订单不存在");
        }
        // 修改退款订单状态
        orderBack.setOrderBackStatus(status);
        orderBack.setAuditTime(new Date());
        orderBack.setAuditUserId(GlobalInput.getCurrentUserId());
        orderBack.setModifyTime(orderBack.getAuditTime());
        orderBackMapper.updateByPrimaryKey(orderBack);

        // 修改订单明细状态
        List<OrderDetail> details = orderDetailMapper.selectByOrderBackId(orderBackId);
        for (OrderDetail detail : details) {
            detail.setStatus(status);
            orderDetailMapper.updateByPrimaryKey(detail);
        }
    }

}
